import {
  createRouter,
  createWebHashHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
} from "vue-router";
import { useSystemStore } from "../store/login";
import { useAppStore } from "../store/app";
import routes from "./module/base-routes";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

// import BaseLayout from '../layouts/BaseLayout.vue';
// import Compage from "../views/compage/index.vue";
import PageBody from "../views/compage/page-body.vue";
import PageBodyTab from "../views/compage/page-body-tab.vue";
import { cloneDeep } from "lodash-es";
import { layer } from "@layui/layui-vue";

// pagegroup = 1 PageBodyTab
// pagegroup = 0 PageBody
const PAGE_GROUP_TAB = 1;

NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

function setDynamicRouter(parent: string, routers: any[]) {
  routers.forEach((_router) => {
    const _Com = cloneDeep(
      _router.meta.pageGroup === PAGE_GROUP_TAB ? PageBodyTab : PageBody,
    );

    // 兼容keep-alive
    if (_router.meta.requireAuth) {
      _Com.__name = _router.path;
    }

    _router.component = _router.meta.requireAuth
      ? _Com
      : () => import("../layouts/BaseLayout.vue");

    _router.component;
    router.addRoute(parent, _router);
    if (_router.children && _router.children.length) {
      setDynamicRouter(parent, _router.children || []);
    }
  });
}

function isExistingRoute(routers: any, path: string) {
  return routers.some((route: { path: string; children: string | any[] }) => {
    if (route.path === path) return true;
    if (route.children && route.children.length) {
      return isExistingRoute(route.children, path);
    }
    return false;
  });
}

/**
 * Router 前置拦截
 *
 * 1.验证 token 存在, 并且有效, 否则 -> login.vue
 * 2.验证 permission 存在, 否则 -> 403.vue
 * 3.验证 router 是否存在, 否则 -> 404.vue
 *
 * @param to 目标
 * @param from 来至
 */
router.beforeEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    const userStore = useSystemStore();
    const userAppStore = useAppStore();
    NProgress.start();
    if (to.path === "/login") {
      next();
      NProgress.done();
      userStore.removeLoginInfo();
    } else if (to.path === "/") {
      if (
        userAppStore.keepAliveList.length > 0 &&
        userAppStore.keepAliveList[0] != undefined &&
        userStore.routers.length > 0
      ) {
        ///TODO  后期需要验证token失效问题 让用户重新登录
        // next({ path: userAppStore.keepAliveList[0] })
        next({ path: "/login" });
        NProgress.done();
        userStore.removeLoginInfo();
      } else {
        next({ path: "/login" });
        NProgress.done();
        userStore.removeLoginInfo();
      }
    } else {
      if (userStore.token == "") {
        next({ path: "/login" });
        NProgress.done();
        userStore.removeLoginInfo();
      }
      const allDynamicRouter = router.getRoutes();
      // 动态添加可访问路由表
      const arrayLength = allDynamicRouter.filter(
        (item: any) => item["path"].indexOf("compage") != -1,
      ).length;
      if (userStore.routers.length > 0 && arrayLength == 0) {
        setDynamicRouter(userStore.routers[0].name, userStore.routers);
      }

      if (to.meta.requireAuth) {
        next();
      } else if (
        to.matched.length == 0 &&
        !isExistingRoute(userStore.routers, to.fullPath)
      ) {
        // next({ path: "/error/404" });
        layer.msg("页面跳转失败，请检查是否有目标页面的访问权限", { icon: 7, time: 1000 })
      } else {
        next();
      }
    }
  },
);

router.beforeResolve((to: RouteLocationNormalized) => {
  if (to.fullPath.includes("compage") && !to.matched.length) {
    return to.fullPath;
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
